//
//  OrderViewController.m
//  Zhiche-Carriage
//
//  Created by LeeBruce on 16/11/1.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

#import "OrderViewController.h"
#import "DriverOrderCell.h"
#import "JRTableVIewSelect.h"
#import "RootViewController.h"
#import "LoginViewController.h"

#import "OrderdetailVC.h"//订单详情
#import "OrdersDetailsVc.h"

#import "PostPictureVC.h"//上传照片
#import "PostWoundPicture.h"
#import "HaveWoundPictureVC.h"

#import "DriverModel.h"

/**
    订单类型
 */
typedef NS_ENUM(NSUInteger, OrdersType)
{
    OrderTypeAllOrders  = 0,        ///全部订单
    OrderTypeNomalOrders = 10,      ///运单
    OrderTypeCompetitionOrders = 20 ///急发单
};

@interface OrderViewController ()
<
    DriverOrderCellDelegate,
    TopBackViewDelegate
>

@property (nonatomic, strong, readwrite) TopBackView *topBackView;

@property (nonatomic, assign, readwrite) OrdersType waybillType;

@end

@implementation OrderViewController
- (void)viewDidLoad {
   
    [super viewDidLoad];
    
    ///1. 添加导航栏
    [self.view addSubview:self.topBackView];
    
    if ([self.hide isEqualToString:@"1"])
    {
        [self downRefresh];
    }
 
}

#pragma mark -
#pragma mark - UITableView协议

static NSString * const identifierCom = @"driverOrderCompetitionCell";
static NSString * const identifierNom = @"driverOrderNomalCell";
/**
    Cell个数
 */
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArray.count;
}
/**
    Cell风格
 */
- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath{
   
    DriverOrderCell *cell;
    
    switch (self.waybillType) {
     
        case OrderTypeCompetitionOrders:
        {
            ///急发单Cell
            cell =  [DriverOrderCell cellHurryOrdersWithTableView:tableView reuseIdentifier:identifierCom];
            cell.model = self.dataArray[indexPath.section];
        }
            break;
        default:
        {
            ///普通订单Cell[目前,只分为两种情况]
            cell =  [DriverOrderCell cellNomalOrdersWithTableView:tableView reuseIdentifier:identifierNom];
            cell.model = self.dataArray[indexPath.section];
        }
            break;
    }

  
    
    cell.delegate = self;
    
    return cell;
}
/**
    Cell点击
 */
- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    [self pushDetailVcWith:self.dataArray[indexPath.section]];
}

/**
    订单Cell代理
 */
- (void)driverOrderCell:(DriverOrderCell *)cell
             orderState:(DriverOrderState)state {
    switch (state) {
        case DriverOrderStateDeatail:
        {
            [self pushDetailVcWith:cell.model];
       
        }
            break;
            /*
                 确认发车(上传照片)
             */
            case DriverOrderStateGiveCar:
        {
            PostPictureVC *postVC = [[PostPictureVC alloc]init];
            
            postVC.isCheckLocalPic = cell.model.isCheckLocalPic;
            
            postVC.orderId = cell.model.ID;
            
            [self.navigationController pushViewController:postVC animated:YES];
         
        }
             break;
        case DriverOrderStateCarWound:
        {

            if ([cell.model.damageAudit integerValue] == 1 ||
                [cell.model.damageAudit integerValue] == 3)
            {
                //待审核0  审核中1  审核通过2 审核未通过3
                HaveWoundPictureVC *woundVC = [[HaveWoundPictureVC alloc]init];
                woundVC.orderId = cell.model.ID;
                [self.navigationController pushViewController:woundVC animated:YES];
                woundVC.damageAudit = cell.model.damageAudit;
                return;
            }
            else
            {
                PostWoundPicture *woundVC = [[PostWoundPicture alloc]init];
                woundVC.orderId = cell.model.ID;
                [self.navigationController pushViewController:woundVC animated:YES];
                
            }
        }
            break;
        default:
            break;
    }
}

/**
    退出订单详情Vc
 */
- (void)pushDetailVcWith:(DriverModel *)model {
    
  
#warning TODO
//    OrdersDetailsVc *detailVC = [[OrdersDetailsVc alloc] init];
    
    OrderdetailVC *detailVC = [[OrderdetailVC alloc] init];
#warning TODO
    detailVC.status = [model.status integerValue];
    
    detailVC.orderID = model.ID;
    
    detailVC.specialRequired = model.specialRequired;
    
    detailVC.waybillType = model.waybillType;
    
    [self.navigationController pushViewController:detailVC animated:YES];
    
 
    
    
}



#pragma mark -
#pragma mark - Lazy
- (TopBackView *)topBackView {
    if (!_topBackView)
    {
        _topBackView = [[TopBackView alloc] initWithFrame:CGRectMake(0, 0, screenWidth, 64)
                                                    title:@"我的运单"
                                        andHaveSmallImage:YES];
        
        
        _topBackView.rightButton.hidden = YES;
        
        _topBackView.delegate = self;
        
        if ([self.hide isEqualToString:@"1"])
        {
            
            ///个人中心 的 我的定点杆
            self.navigationController.interactivePopGestureRecognizer.enabled = YES;
            
            self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
            
            _topBackView.leftButton.hidden = NO;
            
            self.tableView.height = screenHeight - 64;
        }
        else
        {
            ///TabbarVc 的 我的订单
            _topBackView.leftButton.hidden = YES;
            
            self.tableView.height = screenHeight - 64 - 48 * kHeight;
        }
        
    }
    return _topBackView;
}
/**
    导航栏左侧点击
 */
- (void)backViewPopViewController {
    
    [self.navigationController popViewControllerAnimated:YES];
}
/**
    导航栏中间点击
 */
- (void)naviCenterItemClick {
    
//    NSLog(@"%f", );
    
    CGRect secFrame = CGRectMake(self.topBackView.naviTitleBtn.x + self.topBackView.naviTitleBtn.width + 7.5, 64.0f, 106.0f*kWidth, 70.0f*kHeight - 2.5f);
    
    __weak typeof(self) weakSelf = self;
   
    [JRTableVIewSelect addJRTableVIewSelectWithWindowFrame:secFrame
                                                selectData:@[@"运单", @"急发单"]
   action:^(NSInteger index)
    {
        weakSelf.tableView.mj_footer.state = MJRefreshStateIdle;
        
        switch (index)
        {
            case 0:
            {
                weakSelf.waybillType = OrderTypeNomalOrders;
                weakSelf.topBackView.naviTitle = @"我的运单";
                [weakSelf downRefresh];
                
            }
                break;
            case 1:
            {
                weakSelf.waybillType = OrderTypeCompetitionOrders;
                weakSelf.topBackView.naviTitle = @"急发单";
                [weakSelf downRefresh];
            }
                break;
            default:
                break;
        }
        
    } animated:YES];
}
/**
    视图将要出现
 */
- (void)viewWillAppear:(BOOL)animated{
   
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:YES];
    
    RootViewController *rootVC = [RootViewController defaultsTabBar];
    
    if ([self.hide isEqualToString:@"1"])
    {
        
        [rootVC setTabBarHidden:YES];
        
    } else {
        
        [rootVC setTabBarHidden:NO];
        
        [self downRefresh];
    }
 
    if ([rootVC.rootString isEqualToString:@"1"]) {
        
        [self present];
        
        rootVC.rootString = @"2";
    }
}

/**
    判断是否登录
 */
- (void)present{
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    
    NSString *string = [userDefaults objectForKey:@"login"];
    
    if (string == nil ) {
        
        LoginViewController *loginVC = [[LoginViewController alloc]init];
        loginVC.topBackView.leftButton.hidden = YES;
        UINavigationController * loginNC = [[UINavigationController alloc]initWithRootViewController:loginVC];
        loginVC.backToFirst = @"1";
        
        [self presentViewController:loginNC animated:YES completion:nil];
        
    }
    
}



#pragma mark -
#pragma mark - 获取服务器数据
/**
 获取所有急发单列表
 ***
 由于继承关系, 第一次加载视图时, 这一步会自定调用
 */

- (void)getDataToServerDownRefresh:(BOOL)isDownRefresh {
    
    if (!self.waybillType)
    {
        if ([[RootViewController defaultsTabBar].orderType integerValue] == OrderTypeCompetitionOrders)
        {
            self.waybillType = OrderTypeCompetitionOrders;
            self.topBackView.naviTitle = @"急发单";
        }
        else
        {
            self.waybillType = OrderTypeNomalOrders;
            self.topBackView.naviTitle = @"我的运单";
        }
    }
    
    NSString *urlString = [NSString stringWithFormat:@"%@?pageNo=%ld&pageSize=%@&waybillType=%@",waybill_list,self.pageNo,@"10", [NSNumber numberWithUnsignedInteger:self.waybillType]];
    
    __weak typeof(self) weakSelf = self;
    
    NSLog(@"%@", urlString);
    [Common requestWithUrlString:urlString contentType:application_json errorShow:YES finished:^(id responseObj) {
        
        self.pageTotal = [responseObj[@"data"][@"page"][@"totalPage"] integerValue];
        
        if ([responseObj[@"success"] boolValue] != NO)
        {
            
            ///1. 判断
            if (isDownRefresh != YES)
            {
                weakSelf.pageNo ++;
                [weakSelf.tableView.mj_footer endRefreshing];
            }
            else
            {
                if (weakSelf.tableView.mj_footer.hidden != NO)
                {
                    weakSelf.tableView.mj_footer.hidden = NO;
                }
                
                weakSelf.pageNo ++;
                
                [weakSelf.dataArray removeAllObjects];
            }

            
            ///2. 解析
            for (NSDictionary *dic in responseObj[@"data"][@"dWaybillList"])
            {
                
                DriverModel *model = [[DriverModel alloc]init];
                
                [model setValuesForKeysWithDictionary:dic];
                
                [self.dataArray addObject:model];
                
            }
            
            ///3. 再判断
            
            if (self.dataArray.count > 0)
            {
                weakSelf.tableView.backgroundView.hidden = YES;
            }
            else
            {
                weakSelf.tableView.backgroundView.hidden = NO;
                weakSelf.tableBackgroundView.label.text = @"暂无运单";
                weakSelf.tableView.mj_footer.hidden = YES;
            }
            
            ///4. 刷新
            [weakSelf.tableView reloadData];
            
            
        }
        else
        {
            [WKProgressHUD popMessage:responseObj[@"message"]
                               inView:weakSelf.view
                             duration:1.5
                             animated:YES];
            
        }
    } failed:^(NSString *errorMsg) {
        if (weakSelf.tableView.mj_footer.hidden != NO)
        {
            weakSelf.tableView.mj_footer.hidden = NO;
        }
        [WKProgressHUD dismissInView:weakSelf.view animated:YES];
        NSLog(@"%@",errorMsg);
    }];
}


- (void)dealloc {
    NSLog(@"销毁");
}



@end
